package com.client.net;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import com.bean.Message;
import com.utils.Config;

public class NetImpl implements INet<Message> {
	
	private Socket socket;
	private ObjectInputStream ois;
	private ObjectOutputStream oos;

	@Override
	public void connect() {
		try {
			socket = new Socket(Config.host, Integer.valueOf(Config.port));
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public Message receive() {
		try {
			ois = new ObjectInputStream(socket.getInputStream());
			Object obj  = ois.readObject();
			return obj != null ? (Message) obj : new Message();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return new Message();
	}

	@Override
	public void writeData(Message t) {
		try {
			oos = new ObjectOutputStream(socket.getOutputStream());
			oos.writeObject(t);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void disconnect() {
		try {
			ois.close();
			oos.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public Message execute(Message t) {
		connect();
		writeData(t);
		return receive();
	}

}
